// pages/luckyDraw/index.js
// import Toast from '@vant/weapp/toast/index';
// 首先弹框让用户选择福利，再转盘抽奖，最后填写联系方式
import Notify from '../../miniprogram_npm/@vant/weapp/notify/notify';
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';

const db = wx.cloud.database()

Page({

    /**
     * 页面的初始数据
     */
    data: {
        open_id:'',
        is_sub_phone: false,
        user_phone: '',
        user_name: '',
        user_addr:'',
        isLottery: false,
        open_id: '',
        showPop: false, // 联系方式校对提醒弹框
        showAmaPop: false, // 显示用户福利选择弹框
        userLikeRadio: '', // 用户福利选择
        isShowLikeConfirm: true, // 是否显示用户福利确认按钮
        hasConfirmLike: false, // 当前用户是否选过感兴趣福利
        showTurnTable: false, // 显示幸运大环盘
        prize: [{
          'name': '\r\tQQ音乐体验一个月',
          'winnning': 0.03,
          'count': 1
        },
        {
          'name': '抖音纪念杯',
          'winnning': 0.04,
          'count': 1
        }, {
          'name': '新片大片点播金\n 6元',
          'winnning': 0.09,
          'count': 5
        }, {
          'name': '数据线',
          'winnning': 0.02,
          'count': 7
        }, 
        {
          'name': '玻璃水杯',
          'winnning': 0.01,
          'count': 3
        }, 
        {
          'name': '植护纸巾',
          'winnning': 0.08,
          'count': 4
        }
      ],
      chance: 2,
      myGift: [],
      canClick: false,
      verifyUserLike(action) {
        console.log('关闭参数', this.data.userLikeRadio, action)
        new Promise((resolve) => {
          setTimeout(() => {
            if ( !this.data.userLikeRadio) {
              resolve(false);
            } else {
              // 拦截取消操作
              resolve(false);
            }
          }, 1000);
        });
      },
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
      this.setData({ verifyUserLike: this.data.verifyUserLike.bind(this) })
      this.onDigConfirm() // 现在改为手动确认用户抽奖次数与权限
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
        this.getUserStatus()
        wx.clearStorageSync()       
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        wx.hideHomeButton()
        // this.testConnect()
        if(!this.data.hasConfirmLike){
          this.setData({ showAmaPop: false }) // 临时false，正式改回
        }
        db.collection('sales').where({
          _id: "bf4a0bf2620880930dda3a4443a64c94" // true line 版本打开，录入app user等信息 todo
        }).get().then( res => {
          console.log('true_sub', res, res.data.length>0, res.data[0].true_sub==false)
          if(res.data.length>0 && res.data[0].true_sub==false){
            console.log('true_sub', res)
            this.setData({ is_sub_phone: true })
          }
          // this.setData({ is_sub_phone: true })
        })
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    getUserStatus(e){
        wx.cloud.callFunction({
          name: 'quickstartFunctions',    
          data: { type: 'getOpenId'},  
        }).then((resp) => {         
          console.log('用户信息-Open_id', resp.result)
          this.setData({ open_id: resp.result.openid })
          db.collection('users').where({
            _openid: this.data.open_id
          }).get().then( res => {
            console.log('UserGetCheck检查是否提交过手机号', res)
            if(res.data == ""){    
              console.log('用户未登录?? 跳转到首页')     
              wx.redirectTo({
                url: '/pages/index/index',
              })   
              return false  
            }else{             
              if( res.data[0].phone >0 ){
                  this.setData({is_sub_phone: true})               
                  wx.showToast({
                    title: '感谢参与',
                  })                                 
                }else{               
                    wx.showToast({
                        title: 'loading',
                      })          
                }
                   
            }
          } ) 
        wx.hideLoading(); }).catch((e) => { console.log('luckydraw-idbug', e)    //  wx.hideLoading();
        });  
    },
    cloudFunc(){
      wx.cloud.callFunction({
        name: 'sumrate',    
        // data: { data:{ a:12, b:19 }},  
      }).then((resp) => { 
        console.log('CLOUD',resp)
        // db.collection('ranking').where({
        //   _id: '9e7z190f1618f80830570b3141db77ee0'
        // }).get().then( res=>{ console.log(res) } )
        try {
          // db.collection('ranking').doc('18ed0968618f8b8204f88ed55ce181f6').get().then( res=>{ console.log(res) } )
          //  .update({
          //      data:{
          //          single_star_list: resp.result.single ,
          //          team_star_list: resp.result.team,
          //          single_count_list: resp.result.count
          //      }
          //  })
         } catch (error) {
           console.log('eee', error)
         }
       }).catch((e) => { console.log('cloudbug', e)  })  //  wx.hideLoading();
    },
    checkSubmit(ee){             
        if(!(/^1(3|4|5|6|7|8|9)\d{9}$/.test(this.data.user_phone))){ 
            wx.showToast({
              title: "手机号码未填写正确",
              icon: 'error'
            })           
        } else if(!this.data.user_name){
          wx.showToast({
            title: "姓名未填写正确",
            icon: 'error'
          })           
        }
        else{
            // 数据库插入手机号，暂时屏蔽，正式上线开启
            // db.collection('users').where({
            //   _openid: this.data.open_id
            // }).update({
            //     data:{
            //         phone: this.data.user_phone,
            //         user_name: this.data.user_name,
            //         user_addr: this.data.user_name
            //     }
            // })
            console.log('phone right')
            this.setData({ showPop: true }) 
            setTimeout(()=>{ this.setData({showPop: false, is_sub_phone: true})
              this.setData({ canClick: true })      
              Dialog.alert({
                message: '提交成功，请您于近期留意手机信息',
                theme: 'round-button',
              })
          }, 400)          
        }
    },
    onPopClose() {
      this.setData({ showPop: false });
    },
    onPhoneChange(ee){
        console.log(ee.detail, this.data.user_phone)
        this.setData({
            user_phone: ee.detail
        })
    },
    onUserNameChange(ee){
      console.log(ee.detail, this.data.user_name)
      this.setData({
        user_name: ee.detail
      })
    },
    onUserAddrChange(ee){
      console.log(ee.detail, this.data.user_addr)
      this.setData({
        user_addr: ee.detail
      })
    },
    rankFunc(){ 
      wx.navigateTo({
        url: '/pages/ranking/index',
      });
    },
    testConnect(){
      let url = 'https://cookcloud.club/error'
      wx.request({
        url: url,
        method: 'GET',
        data:{},
        header:{ "content-type": "application/json" },
        timeout:5000,
        //  成功回调
        success: res => {
          // wx.hideLoading()
          console.log('ddaata', res.data)
          // resolve(res.data)
        },
        //  错误回调
        fail: err => {
          // wx.hideLoading()
          
          wx.showToast({
            title: '网络错误！',
            icon:'error',
            duration: 2000
          })
          // reject(err)
  
          console.log('cuowy');
        },
        //  请求完成回调
        complete: () => {
          // wx.hideLoading()
        }
      });
    },
    onUserLikeChange(event) {
      this.setData({
        userLikeRadio: event.detail,
      },()=>{        
        this.setData({ isShowLikeConfirm: true})
      });
    },
    onLikeConfirmClick(event) {
      const { name } = event.currentTarget.dataset;
      console.log('onLikeConfirmClick', name)
      this.setData({
        userLikeRadio: name,
        isShowLikeConfirm: true
      });
    },
    onDigConfirm(){
      //  let userLike = this.data.userLikeRadio
      //  if (!userLike){
      //    wx.showToast({
      //      title: '您还未选择福利',
      //      showAmaPop: true
      //    })
      //    return
      //  }
      // db.collection('users').where({ // 入库用户喜爱的福利
      //       _openid: this.data.open_id
      //     }).update({
      //         data:{
      //            user_want_gift: this.data.userLikeRadio 
      //         }
      //     })
      this.sentLuckyServer('')
      this.setData({
        hasConfirmLike: true,
        showTurnTable: true
      })
      Notify({message:'请留下您的联系方式，为您准备后续专属福利',
        duration: 30000,    
    });
    },
    _getMyLucky() {
      getMyLucky().then(res => {
        let chance = res.lucky
        this.setData({
          chance
        })
      })
    },
    _sendLucky(e) {
      let prize = e.detail.count
      let cName = e.detail.name
      let message = prize > 0 ? `恭喜你抽中了 \n ${cName}`: '非常遗憾，你没抽中'
      this.sentLuckyServer('finsh_once')
      this.setData({ myGift: [cName]})
      Dialog.alert({
        message: message,
        theme: 'round-button',
      }).then(() => {
        this.selectComponent('#myTurnTable').onClear()
        this.checkIsNoneLuckyServer(this.data.chance)
      }).then(() => { })
    },
    // 发送/获取云数据库当前用户剩余抽奖数(status 状态 finsh_once时扣除一次，抽奖时用，默认参数只查询不扣除 )
    sentLuckyServer(status){
      wx.cloud.callFunction({
        name: 'quickstartFunctions',    
        data: { type: 'getOpenId'}, 
      }).then((resp) => {
        this.setData({ open_id: resp.result.openid }) // console.log('OPID',e.detail.userInfo) 
        db.collection('users').where({
          _openid: this.data.open_id
        }).get().then( res => {
            console.log('RES DATA =>', res.data[0]['luckyChance'] )
            if(res.data[0]){    //  如果用户字段存在？
              console.log('init清零状态', curChance , typeof(curChance) == 'undefined')
              let curChance = res.data[0]['luckyChance']
              if(curChance==0 || curChance<1 || curChance=='undefined' || typeof(curChance) == 'undefined'){
                console.log('CurChance 清零状态', curChance )
                this.setData({
                  chance: 0,
                  showTurnTable:false,
                  showAmaPop: false
                })
                // this.setData({showTurnTable:false})
                return 
              }else{
                if(status=='finsh_once'){
                  curChance = curChance - 1     
                  db.collection('users').where({
                    _openid: this.data.open_id
                  }).update( {
                      data:{
                        luckyChance: curChance ,// 修改次数
                        myGift: db.command.push(this.data.myGift)
                      }
                  } )             
                }
                this.setData({ chance: curChance })
              }
            }  }
         ) 
      wx.hideLoading(  );
      }).catch((e) => {
        console.log('转盘数据库云函数index-idbug', e)   
      //  wx.hideLoading();
      });
    },
    // getLuckServer(){
      
    // },
    // 没有抽奖机会
    onNoneChance () {
      Dialog.alert({
        message: '您已经没有抽奖机会',
        theme: 'round-button',
      })
      this.checkIsNoneLuckyServer(this.data.chance)
    },
    checkIsNoneLuckyServer(curChance){
      if(curChance==0 || curChance<1 || curChance=='undefined' || typeof(curChance) == 'undefined'){
        console.log('YYYYYYYYYYYY清零状态', curChance )
        this.setData({
          chance: 0,
          showTurnTable:false,
          showAmaPop: false
        }) 
      }
    },

    verify(action) {
      console.log('关闭参数', action)
      new Promise((resolve) => {
        setTimeout(() => {
          if (action === 'confirm') {
            resolve(false);
          } else {
            // 拦截取消操作
            resolve(false);
          }
        }, 1000);
      });
    },
    onTurnTableHandsOver(){ // 手动结束转盘
      this.setData({ showTurnTable: false })
    },
    // onDigClose( event ){
    //   console.log('关闭参数', event.detail)
    //   if(event.detail == 'confirm'){ 
    //   }
    // },
    onDigClose (action) {
      console.log('关闭参数', action)
      // if (action === 'confirm') {
      //   return false
      // }
      
    },
    
})